package android.dj.lbscamera.network;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import android.dj.lbscamera.utils.UseUtils;
import android.graphics.Bitmap;

public class ResourceManager {

	private static final String BASEURL = "http://gateway.ilovepostcard.com/action.aspx";
	private static final String API_LOGIN = "UserLogin";
	private static final String API_GETUSERINFO = "GetUserInfo";
	private static final String API_REGISTER = "UserRegister";
	private static final String API_GETUSERHEADIMG = "GetUserHeadImg";
	private static final String API_GETUPLOADSKEY = "GetUploadSKey";
	private static final String API_CREATEPOSTCARD = "CreatePostcard";
	private static final String API_GETMYNEARPOSTCARD = "GetMyNearPostcard";
	private static final String API_GETMYPOSTCARD = "GetMyPostcard";
	private static final String API_SHAREPOSTCARD = "SharePostcard";
	private static final String API_UPDATEUSERINFO = "UpdateUserInfo";
	private static final String API_LISTCITY = "ListCity";
	private static final String API_COMMENT = "PostProposal";

	private static ResourceManager mInstance;

	private ResourceManager() {
	}

	public static ResourceManager getInstance() {
		if (mInstance != null) {
			mInstance = null;
		}
		mInstance = new ResourceManager();
		return mInstance;
	}

	public String doLogin(String uname, String pwd) throws Exception {
		HashMap<String, String> loginArgs = new HashMap<String, String>();
		try {
			loginArgs.put("do", API_LOGIN);
			loginArgs.put("uname", uname);
			loginArgs.put("pwd", UseUtils.getMD5(pwd));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		String url = createURL(loginArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doGetUserInfo(String uname, String uid) throws Exception {
		HashMap<String, String> userinfoArgs = new HashMap<String, String>();
		userinfoArgs.put("do", API_GETUSERINFO);
		userinfoArgs.put("uname", uname);
		userinfoArgs.put("uid", uid);
		String url = createURL(userinfoArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doUpdateUserInfo(String uid, String sex, String birthday,
			String province, String city, String introduction) throws Exception {
		HashMap<String, String> updateArgs = new HashMap<String, String>();
		updateArgs.put("do", API_UPDATEUSERINFO);
		updateArgs.put("uid", uid);
		updateArgs.put("sex", sex);
		updateArgs.put("birthday", birthday);
		updateArgs.put("province", province);
		updateArgs.put("city", city);
		updateArgs.put("introduction", introduction);
		String url = createURL(updateArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doRegister(String uname, String pwd, String nickname)
			throws Exception {
		HashMap<String, String> registerArgs = new HashMap<String, String>();
		registerArgs.put("do", API_REGISTER);
		registerArgs.put("uname", uname);
		registerArgs.put("pwd", pwd);
		registerArgs.put("nickname", nickname);
		String url = createURL(registerArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doGetUserHeadImg(String uid) throws Exception {
		HashMap<String, String> getUserHeadImgArgs = new HashMap<String, String>();
		getUserHeadImgArgs.put("do", API_GETUSERHEADIMG);
		getUserHeadImgArgs.put("uid", uid);
		String url = createURL(getUserHeadImgArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doGetUploadSKey() throws Exception {
		HashMap<String, String> getUploadSKeyArgs = new HashMap<String, String>();
		getUploadSKeyArgs.put("do", API_GETUPLOADSKEY);
		String url = createURL(getUploadSKeyArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}
	
	public String doGetListCity() throws Exception {
		HashMap<String, String> getListCity = new HashMap<String, String>();
		getListCity.put("do", API_LISTCITY);
		String url = createURL(getListCity);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doCreatePostcard(String uid, String tofriendwords,
			String story, String isshowwords, String latitude,
			String longitude, String skey) throws Exception {
		HashMap<String, String> createPostcardArgs = new HashMap<String, String>();
		createPostcardArgs.put("do", API_CREATEPOSTCARD);
		createPostcardArgs.put("uid", uid);
		createPostcardArgs.put("tofriendwords", tofriendwords);
		createPostcardArgs.put("story", story);
		createPostcardArgs.put("isshowwords", isshowwords);
		createPostcardArgs.put("latitude", latitude);
		createPostcardArgs.put("longitude", longitude);
		createPostcardArgs.put("skey", skey);
		String url = createURL(createPostcardArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doGetMyNearPostcard(String uid, String latitude,
			String longitude, String pi, String pc) throws Exception {
		HashMap<String, String> myNearPostcardArgs = new HashMap<String, String>();
		myNearPostcardArgs.put("do", API_GETMYNEARPOSTCARD);
		myNearPostcardArgs.put("uid", uid);
		myNearPostcardArgs.put("latitude", latitude);
		myNearPostcardArgs.put("longitude", longitude);
		myNearPostcardArgs.put("pi", pi);
		myNearPostcardArgs.put("pc", pc);
		String url = createURL(myNearPostcardArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doGetMyPostcard(String uid, String pi, String pc)
			throws Exception {
		HashMap<String, String> myPostcardArgs = new HashMap<String, String>();
		myPostcardArgs.put("do", API_GETMYPOSTCARD);
		myPostcardArgs.put("uid", uid);
		myPostcardArgs.put("pi", pi);
		myPostcardArgs.put("pc", pc);
		String url = createURL(myPostcardArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	public String doSharePostcard(String uid, String postcardid, String receiver)
			throws Exception {
		HashMap<String, String> sharePostcardArgs = new HashMap<String, String>();
		sharePostcardArgs.put("do", API_SHAREPOSTCARD);
		sharePostcardArgs.put("uid", uid);
		sharePostcardArgs.put("postcardid", postcardid);
		sharePostcardArgs.put("receiver", receiver);
		String url = createURL(sharePostcardArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}
	
	public String doComment(String uid, String body) throws Exception{
		HashMap<String, String> commentArgs = new HashMap<String, String>();
		commentArgs.put("do", API_COMMENT);
		commentArgs.put("uid", uid);
		commentArgs.put("body", body);
		String url = createURL(commentArgs);
		return ServerManager.getInstance().httpGetRequest(url);
	}

	private File convertBitmapToFile(File file, Bitmap bitmap) {
		// File f= new File("/sdcard/temp.png");
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 0, out)) {
				out.flush();
				out.close();
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return file;
	}

	public String uploadUserImg(String type, String filename, String skey, String userid,
			Bitmap bitmap) {
		String result = null;
		String actionUrl = BASEURL + "?do=UploadFile";
		try {
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			con.setRequestMethod("POST");
			con.addRequestProperty("type", type);
			con.addRequestProperty("filename", filename);
			con.addRequestProperty("skey", skey);
			con.addRequestProperty("uid", userid);
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			File fold = new File("/sdcard/dujun");
			if (!fold.exists()) {
				fold.mkdir();
			}
			File file = new File("/sdcard/dujun/" + filename);
			file = convertBitmapToFile(file, bitmap);
			FileInputStream fStream = new FileInputStream(file);
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = fStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			fStream.close();
			ds.flush();
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			result = new String(b);
			ds.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return result;
	}

	private String createURL(HashMap<String, String> argsMap) {
		String url = BASEURL;
		Iterator iter = argsMap.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey();
			String val = (String) entry.getValue();
			if (url.indexOf('?') == -1) {
				url += "?" + key + "=" + val;
			} else {
				url += "&" + key + "=" + val;
			}
		}
		return url;
	}

}
